<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once('src/facebook.php');

class Player extends CI_Controller {
	
	var $data;	
	var $settings;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('community_model');
		$this->load->model('player_model');
		$this->load->model('feeds');
		$this->load->helper('text');
		$this->config->load('fbconfig');
	}
	
	public function index()
	{
		$this->load_player('digradio');		
	}
	
	public function load_player($community,$audio_only = 0)
	{
		
		$this->community = $this->community_model->fetch_community_data($community);			
		$this->config->load('themes');
        $this->config->load('fbconfig');
        $this->data['fb_app_id'] = $this->config->item('app_id');
		$theme = $this->config->item($community);
		if($theme == "" || !isset($theme))
			$theme = $this->config->item('global_theme');
		
        $this->data['community_image'] = $this->community->strPicture;
		$this->load->config("player");
		$this->data['player_settings'] = $this->config->item("player_settings");		
		
		$this->data['css_dir'] = base_url()."assets/themes/".$theme."/css/";
		$this->data['js_dir'] = base_url()."assets/themes/".$theme."/js/";
        $this->data['img_dir'] = base_url()."assets/themes/".$theme."/images/";
		$this->theme = $theme;
        
        $this->data['title'] = strtoupper($community).' Player';
		
		switch($community)
        {
            case 'digradio':
                $this->data['station_id'] = 'DIG_RADIO';
                break;
             case 'planetjazz':
                $this->data['station_id'] = 'PLANET_JAZZ';
                break;
             case 'riceradio':
                $this->data['station_id'] = 'RICE_RADIO';
                break;
             case 'yoradio':
                $this->data['station_id'] = 'YO_RADIO';
        }
		//load data for communities
        if(!$audio_only)
        {
            $video = $this->community_model->get_featured_video(get_type_id('show'),$this->community->intID);
            if(!empty($video)){
                $this->data['video'] = $video->strYoutubeId;
                $this->data['video_data'] = $video;
            }
        }
        
        $this->data['videos'] = $this->player_model->get_all_videos();
        $this->data['most_requested'] = $this->player_model->get_most_requested($this->community->intID);
        $this->data['stream_url'] = $this->community->strStreamUrl;
        $this->data['community'] = $community;
		$this->load->view('header',$this->data);
		$this->load->view('player',$this->data);		
		$this->load->view('footer',$this->data);
		$this->load->view('player_js',$this->data);
        
		
	}
	
    function process_song_request($community)
    {
        $logged_in = $this->session->userdata('user_logged');
        if($logged_in!='')
        {
            $song = $this->input->post('song'); 
            $community = $this->community_model->fetch_community_data($community);
            if($this->player_model->process_request($song,$community->intID))
                $data['message'] =  'success';
            else
                $data['message'] =  'not expired';   
        }
        else
        {
            $data['message'] = 'error';
        }
        echo json_encode($data);
    }
    
	function fetch_song_data($ajax = TRUE , $station = '') {
    // Validate the call

        $this->load->config("player");

        //TODO Check API Key
        if(!$station)
            $station = $this->input->post('station');

			
        $this->load->config(get_name_from_id($station,'tb_mas_community'));        
		$this->load->library('shoutcast');
		$this->load->helper('voscast');

        $server_ip = $this->config->item('server_ip');
        $server_port = $this->config->item('server_port');
        $server_pass = $this->config->item('server_pass');
        $server_fail = $this->config->item('server_fail');
		
		
        $this->shoutcast->setDetails($server_ip, $server_port, $server_pass, 1);		
		
	
        if ($stats = $this->shoutcast->getSevenHTML()) {						
			//print_r($stats->songTitle);
			$song = $this->player_model->get_song_meta(replace_special_characters($stats->songTitle));
            
			if(empty($song))
			{
				$tuner_data = array(
					"status" => 1,					
				);
			}
			else
			{				
				$album_art = $this->player_model->get_album_art($song['fk-tb_mas_albums']);
				$this->player_model->update_last_played($song['intID']);
				$tuner_data = array(
					"status" => 2,
					"artist" => strtolower($song['strArtist']),
					"songtitle" =>strtolower($song['strSongTitle']),
					"bitrate"=>$stats->bitrate,
					"currentListeners" =>$stats->currentListeners,
					"albumArt" => $album_art
					
				);
			}
        }else {
            $tuner_data = array(
					"status" => 0
				);
        }
		
		
		
        if($ajax) {
            echo json_encode($tuner_data);
        }else {
            return $tuner_data;
        }
    }
	
	public function song_object($song_id)
	{
		$this->data['song_meta'] = $this->player_model->get_song_by_id($song_id);
		$this->data['song_meta']['album_art'] = $this->player_model->get_album_art($this->data['song_meta']['fk-tb_mas_albums']);
		$this->data['facebook_meta'] = Array('app_id'=>$this->config->item('app_id'),'app_secret'=>$this->config->item('app_secret'));
		$this->load->view('object',$this->data);
		
	}
	
	public function like_action($song_id)
	{
		$config = array();
		$config['appId'] = $this->config->item('app_id');
		$config['secret'] = $this->config->item('app_secret');
		$facebook = new Facebook($config);

		$user = $facebook->api('/me');
		
		//publish like action
		$response = $facebook->api(
		  'me/og.likes',
		  'POST',
		  array(
			'object' => base_url().'player/song_object/'.$song_id
		  )
		); 
		
		//process response
		$data = $facebook->api($response['id'],'GET');
		
		//save to database
		print_r($data);
	}
	
	public function login_fb()
	{
		$this->config->load('fbconfig');
		$app_id = $this->config->item('app_id');
		$app_secret = $this->config->item('app_secret');
		$facebook = new Facebook(array(
			  'appId'  => $app_id,
			  'secret' => $app_secret
			  
		));
		$params = array(
			'scope' => 'user_status,publish_stream,publish_actions,user_photos,email,offline_access,user_photos,user_birthday,user_location,friends_likes,read_stream',
			'redirect_uri'=>base_url().'player/fb_connect'
		);
		
		$this->data['fb_login_link'] = $facebook->getLoginUrl($params);
		echo '<a href="'.$this->data['fb_login_link'].'">FACEBOOK LOGIN</a>';
	}
	
	public function fb_connect()
	{
		//$this->load->model('data_fetcher');
		$this->config->load('fbconfig');
		$app_id = $this->config->item('app_id');
		$app_secret = $this->config->item('app_secret');
			
		$facebook = new Facebook(array(
			  'appId'  => $app_id,
			  'secret' => $app_secret
			  
		));
		
		$user = $facebook->getUser();
		$facebook->setExtendedAccessToken();
		
		if($user) {
		  try{
				// Proceed knowing you have a logged in user who's authenticated.
				$user = $facebook->api('/me');
				$params = array( 'next' => base_url().'accounts/logoutfb' );
				$logouturl = $facebook->getLogoutUrl($params); // $params is optional. 										
				$this->session->set_userdata('logouturl',$logouturl);
				$this->session->set_userdata('getAppID',$facebook->getAppID());;
				if($user['id']!=NULL){
					$salt = 'c9s1';
					$pass = substr(md5(uniqid()), 0, 8).$salt;
					strtoupper($user['gender'][0]);
					$userdata = Array('strFBUID' => $user['id'],
									  'strFirstName' => $user['first_name'],
									  'strLastName' => $user['last_name'],
									  'strMI' => isset($user['middle_name'][0])?$user['middle_name'][0]:'',
									  'dateBirtDate' => date("Y-m-d H:i:s", strtotime($user['birthday'])),
									  'strEmail' => $user['email'],
									  'strLocation' => isset($user['location']['name'])?$user['location']['name']:'',
									  'enumGender' => $user['gender'],
									  'enumRegistrationType' => 'Facebook',
									  'dateDateRegistered' => date("Y-m-d H:i:s"),
									  'dateLastLogin' => date("Y-m-d H:i:s"),
					);
					$this->session->set_userdata('userid',$user['id']);
					redirect(base_url().'player/like_action/1');
					//$this->session->set_userdata('fb_inserted',$this->data_fetcher->insert_fb_user($userdata));
					
					
					//check if userdata is already in db, if not, insert them and return data, else return 0;
					//$test = $this->data_fetcher->insert_fb_user($userdata);
					
					//pull userdata from database, and store to session
					//$data = $this->data_fetcher->get_from_email($user['email']);
					//foreach($data as $key=>$value)
					//{
					//	$this->session->set_userdata($key,$value);			
					//}
					//$this->session->set_userdata('logged_in',1);
					
				}					
			}catch (FacebookApiException $e) {
			  error_log($e);
			  $user = null;
		  }
		}
		
		if (!$user) {
			
		}
		
	}
}